// Copyright (c) MatrixFramework. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Volo.Abp.Domain.Entities.Auditing;
using Volo.Abp.MultiTenancy;

namespace MatrixFramework.Photos.Domain.Entities;

/// <summary>
/// 照片批量操作实体
/// 支持各种批量处理任务的调度和执行
/// </summary>
public class PhotoBatchOperation : FullAuditedAggregateRoot<Guid>, IMultiTenant
{
    /// <summary>
    /// 租户ID
    /// </summary>
    public virtual Guid? TenantId { get; protected set; }

    /// <summary>
    /// 操作名称
    /// </summary>
    [Required]
    [MaxLength(200)]
    public virtual string Name { get; protected set; } = string.Empty;

    /// <summary>
    /// 操作描述
    /// </summary>
    [MaxLength(1000)]
    public virtual string? Description { get; protected set; }

    /// <summary>
    /// 操作类型
    /// </summary>
    public virtual BatchOperationType OperationType { get; protected set; }

    /// <summary>
    /// 操作状态
    /// </summary>
    public virtual BatchOperationStatus Status { get; protected set; }

    /// <summary>
    /// 优先级
    /// </summary>
    public virtual int Priority { get; protected set; }

    /// <summary>
    /// 操作参数（JSON格式）
    /// </summary>
    public virtual string? Parameters { get; protected set; }

    /// <summary>
    /// 照片ID列表（JSON格式）
    /// </summary>
    public virtual string PhotoIds { get; protected set; } = string.Empty;

    /// <summary>
    /// 总数量
    /// </summary>
    public virtual int TotalCount { get; protected set; }

    /// <summary>
    /// 已处理数量
    /// </summary>
    public virtual int ProcessedCount { get; protected set; }

    /// <summary>
    /// 成功数量
    /// </summary>
    public virtual int SuccessCount { get; protected set; }

    /// <summary>
    /// 失败数量
    /// </summary>
    public virtual int FailureCount { get; protected set; }

    /// <summary>
    /// 跳过数量
    /// </summary>
    public virtual int SkippedCount { get; protected set; }

    /// <summary>
    /// 开始时间
    /// </summary>
    public virtual DateTime? StartedAt { get; protected set; }

    /// <summary>
    /// 完成时间
    /// </summary>
    public virtual DateTime? CompletedAt { get; protected set; }

    /// <summary>
    /// 预计完成时间
    /// </summary>
    public virtual DateTime? EstimatedCompletionAt { get; protected set; }

    /// <summary>
    /// 进度百分比
    /// </summary>
    public virtual double ProgressPercentage
    {
        get
        {
            if (TotalCount == 0) return 0;
            return (double)ProcessedCount / TotalCount * 100;
        }
    }

    /// <summary>
    /// 操作结果摘要
    /// </summary>
    [MaxLength(2000)]
    public virtual string? ResultSummary { get; protected set; }

    /// <summary>
    /// 错误信息
    /// </summary>
    [MaxLength(2000)]
    public virtual string? ErrorMessage { get; protected set; }

    /// <summary>
    /// 创建者ID
    /// </summary>
    public virtual Guid? CreatorId { get; protected set; }

    /// <summary>
    /// 操作项列表
    /// </summary>
    public virtual ICollection<PhotoBatchOperationItem> Items { get; protected set; } = new List<PhotoBatchOperationItem>();

    #region 构造函数

    /// <summary>
    /// 参数化构造函数
    /// </summary>
    /// <param name="id">操作ID</param>
    /// <param name="tenantId">租户ID</param>
    /// <param name="name">操作名称</param>
    /// <param name="operationType">操作类型</param>
    /// <param name="photoIds">照片ID列表</param>
    /// <param name="creatorId">创建者ID</param>
    public PhotoBatchOperation(
        Guid id,
        Guid? tenantId,
        string name,
        BatchOperationType operationType,
        IEnumerable<Guid> photoIds,
        Guid? creatorId = null) : base(id)
    {
        TenantId = tenantId;
        Name = name;
        OperationType = operationType;
        PhotoIds = System.Text.Json.JsonSerializer.Serialize(photoIds);
        TotalCount = System.Linq.Enumerable.Count(photoIds);
        CreatorId = creatorId;
        Status = BatchOperationStatus.Pending;
        Priority = 5; // 默认中等优先级
    }

    /// <summary>
    /// 无参构造函数（用于EF Core）
    /// </summary>
    protected PhotoBatchOperation()
    {
        Items = new List<PhotoBatchOperationItem>();
    }

    #endregion

    #region 业务方法

    /// <summary>
    /// 开始执行
    /// </summary>
    public virtual void Start()
    {
        if (Status != BatchOperationStatus.Pending)
        {
            throw new InvalidOperationException("只能对待执行状态的操作开始执行");
        }

        Status = BatchOperationStatus.Running;
        StartedAt = DateTime.UtcNow;
    }

    /// <summary>
    /// 暂停执行
    /// </summary>
    public virtual void Pause()
    {
        if (Status != BatchOperationStatus.Running)
        {
            throw new InvalidOperationException("只能对运行中状态的操作暂停");
        }

        Status = BatchOperationStatus.Paused;
    }

    /// <summary>
    /// 恢复执行
    /// </summary>
    public virtual void Resume()
    {
        if (Status != BatchOperationStatus.Paused)
        {
            throw new InvalidOperationException("只能对暂停状态的操作恢复");
        }

        Status = BatchOperationStatus.Running;
    }

    /// <summary>
    /// 完成执行
    /// </summary>
    /// <param name="resultSummary">结果摘要</param>
    public virtual void Complete(string? resultSummary = null)
    {
        if (Status != BatchOperationStatus.Running && Status != BatchOperationStatus.Paused)
        {
            throw new InvalidOperationException("只能对运行中或暂停状态的操作完成");
        }

        Status = BatchOperationStatus.Completed;
        CompletedAt = DateTime.UtcNow;
        ResultSummary = resultSummary;
        UpdateProgress();
    }

    /// <summary>
    /// 执行失败
    /// </summary>
    /// <param name="errorMessage">错误信息</param>
    public virtual void Fail(string errorMessage)
    {
        Status = BatchOperationStatus.Failed;
        CompletedAt = DateTime.UtcNow;
        ErrorMessage = errorMessage;
    }

    /// <summary>
    /// 取消操作
    /// </summary>
    public virtual void Cancel()
    {
        if (Status == BatchOperationStatus.Completed || Status == BatchOperationStatus.Failed)
        {
            throw new InvalidOperationException("已完成或失败的操作不能取消");
        }

        Status = BatchOperationStatus.Cancelled;
        CompletedAt = DateTime.UtcNow;
    }

    /// <summary>
    /// 更新进度
    /// </summary>
    public virtual void UpdateProgress()
    {
        ProcessedCount = SuccessCount + FailureCount + SkippedCount;
    }

    /// <summary>
    /// 增加成功计数
    /// </summary>
    public virtual void IncrementSuccess()
    {
        SuccessCount++;
        UpdateProgress();
    }

    /// <summary>
    /// 增加失败计数
    /// </summary>
    public virtual void IncrementFailure()
    {
        FailureCount++;
        UpdateProgress();
    }

    /// <summary>
    /// 增加跳过计数
    /// </summary>
    public virtual void IncrementSkipped()
    {
        SkippedCount++;
        UpdateProgress();
    }

    /// <summary>
    /// 设置优先级
    /// </summary>
    /// <param name="priority">优先级（1-10，10最高）</param>
    public virtual void SetPriority(int priority)
    {
        Priority = Math.Clamp(priority, 1, 10);
    }

    #endregion
}

/// <summary>
/// 批量操作类型枚举
/// </summary>
public enum BatchOperationType
{
    /// <summary>
    /// 未知
    /// </summary>
    Unknown = 0,

    /// <summary>
    /// 批量导入
    /// </summary>
    Import = 1,

    /// <summary>
    /// 批量导出
    /// </summary>
    Export = 2,

    /// <summary>
    /// 批量删除
    /// </summary>
    Delete = 3,

    /// <summary>
    /// 批量重命名
    /// </summary>
    Rename = 4,

    /// <summary>
    /// 批量移动
    /// </summary>
    Move = 5,

    /// <summary>
    /// 批量标签
    /// </summary>
    Tag = 6,

    /// <summary>
    /// 批量压缩
    /// </summary>
    Compress = 7,

    /// <summary>
    /// 批量生成缩略图
    /// </summary>
    GenerateThumbnails = 8,

    /// <summary>
    /// 批量元数据提取
    /// </summary>
    ExtractMetadata = 9,

    /// <summary>
    /// 批量AI分析
    /// </summary>
    AIAnalysis = 10,

    /// <summary>
    /// 自定义操作
    /// </summary>
    Custom = 99
}

/// <summary>
/// 批量操作状态枚举
/// </summary>
public enum BatchOperationStatus
{
    /// <summary>
    /// 待执行
    /// </summary>
    Pending = 0,

    /// <summary>
    /// 运行中
    /// </summary>
    Running = 1,

    /// <summary>
    /// 已暂停
    /// </summary>
    Paused = 2,

    /// <summary>
    /// 已完成
    /// </summary>
    Completed = 3,

    /// <summary>
    /// 失败
    /// </summary>
    Failed = 4,

    /// <summary>
    /// 已取消
    /// </summary>
    Cancelled = 5
}